package com.guojian.http.handle;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.eclipse.jetty.http.HttpHeader;

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class HttpJettyResponseBuilder {

	private HttpServletResponse httpServletResponse;
	private CloseableHttpResponse closeableHttpResponse;

	public HttpJettyServletResponseWrapper buildHttpServletResponse() throws IOException {
		initTargetHttpResponseHeaders(getCloseableHttpResponse(), getHttpServletResponse());
		HttpEntity entity = getCloseableHttpResponse().getEntity();
		if (entity != null) {
			return new HttpJettyServletResponseWrapper(getHttpServletResponse(), EntityUtils.toByteArray(entity));
		}
		return new HttpJettyServletResponseWrapper(getHttpServletResponse(), null);
	}

	public byte[] getResponseContent() throws IOException {
		initTargetHttpResponseHeaders(getCloseableHttpResponse(), getHttpServletResponse());
		HttpEntity entity = getCloseableHttpResponse().getEntity();
		if (entity != null) {
			return EntityUtils.toByteArray(entity);
		}
		return new byte[0];
	}

	private void initTargetHttpResponseHeaders(CloseableHttpResponse closeableHttpResponse, HttpServletResponse targetHttpResponse) {

		closeableHttpResponse.removeHeaders(HttpHeader.DATE.asString());
		closeableHttpResponse.removeHeaders(HttpHeader.CONNECTION.asString());
		closeableHttpResponse.removeHeaders(HttpHeader.SERVER.asString());

		targetHttpResponse.setStatus(closeableHttpResponse.getStatusLine().getStatusCode());
		Header[] headers = closeableHttpResponse.getAllHeaders();
		for (Header header : headers) {
			targetHttpResponse.addHeader(header.getName(), header.getValue());
		}

	}

}
